﻿/*
 * ShpConnection
 * 
 * initial implementation : 20.9.2008
 *
 * Copyright (c) Adam Sida, asida@centrum.cz.
 * All rights reserved.
 * 
 * for license see Petra.Gis.License.txt
 */
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Petra.Gis.DataServices;
//using Petra.Gis.ReferenceSystemServices;


namespace Petra.Gis.DataServices.SHP
{
  public partial class ShpConnection : SpatialDbConnection
  {
    //protected FileStream _filestream;
    protected string _dataFolder;
    protected string _csAuthority;
    protected string _csCode;
    protected string _csUnits;
    protected string _textEncoding;
    protected Dictionary<string, string> _shps;
    protected bool _connOpen;



    public ShpConnection()
    {

    }




    public ShpConnection(string connectionString)
    {
      this.ConnectionString = connectionString;
    }




    public override void Open()
    {

      DirectoryInfo dir = new System.IO.DirectoryInfo(_path);
 
      FileInfo[] shps = dir.GetFiles("*.shp");

      if(shps.Length == 0)
        throw new ArgumentException("invalid path, no shp files");

      _shps = new Dictionary<string, string>();

      foreach (System.IO.FileInfo f in shps) 
      {
        _shps.Add(Path.GetFileNameWithoutExtension (f.Name), f.FullName);
      }
      _connOpen = true;

    }




    public override void Close()
    {
      _connOpen = false;
    }




    protected override DbCommand CreateDbCommand()
    {
      return this.CreateCommand();
    }





    new public ShpSelectCommand CreateCommand()
    {
      ShpSelectCommand result = new ShpSelectCommand();
      result.Connection = this;
      return result;
    }




    protected string _connectionString;


    public override string ConnectionString
    {
      get { return _connectionString; }
      set
      {
        //parse connection string
        // eg. DataFolder = c:\temp\testSHP; CoordinateSystemAuthority=INGR ; CoordinateSystemCode=49  ; CoordinateStorageUnits=metre;
        parseConnString(value);
        _connectionString = value;
      }
    }




    protected string _path;


    public override string DataSource
    {
      get { return _path; }
    }





    public override string Database
    {
      get { return _path; }
    }





    public override void ChangeDatabase(string databaseName)
    {
      //_sqlConnection.ChangeDatabase(databaseName);
    }



    protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
    {
      //return this.BeginTransaction();
      throw new ApplicationException("transactions not available on shp");
    }




    new public DbTransaction BeginTransaction()
    {
      //return _sqlConnection.BeginTransaction();
      throw new ApplicationException("transactions not available on shp");
    }




    public override string ServerVersion
    {
      get { return "0.99"; }
    }





    public override ConnectionState State
    {
      get
      {
        if (_connOpen)
          return ConnectionState.Open;
        else
          return ConnectionState.Closed;
      }
    }




    //public override ConnectionState XState
    //{
    //  get { return this.State; }
    //  set
    //  {
    //    recoverConnectionState(value);
    //  }
    //}





    //protected void recoverConnectionState(ConnectionState savedState)
    //{
    //  if (savedState == ConnectionState.Open && _connectionString != "")
    //  {
    //    this.Open();
    //  }
    //}





    protected void parseConnString(string cstr)
    {
      // eg. DataFolder = c:\temp\testSHP; CoordinateSystemAuthority=INGR ; CoordinateSystemCode=49  ; CoordinateStorageUnits=metre;
      // in addition there might be TextEncoding = xxxx, where xxxx is numeric value
      // represents valid encoding
      // clasic split parse, params might have variable order...
      string[] citems = cstr.Split(';');

      foreach (string citem in citems)
      {
        string[] subitems = citem.Split('=');

        if (subitems.Length != 2)
          return;

        if (subitems[0].Trim().ToLower() == "data source")
          _path = subitems[1].Trim();

        else if(subitems[0].Trim().ToLower() == "coordinatesystemauthority")
          _csAuthority = subitems[1].Trim();

        else if (subitems[0].Trim().ToLower() == "coordinatesystemcode")
          _csCode = subitems[1].Trim();

        else if (subitems[0].Trim().ToLower() == "coordinatestorageunits")
          _csUnits = subitems[1].Trim();

        else if (subitems[0].Trim().ToLower() == "textencoding")
        {
          _textEncoding = subitems[1].Trim();
          //int tt = System.Convert.ToInt32(_textEncoding);
          this.Extensions.Add("TextEncoding", System.Text.Encoding.GetEncoding(System.Convert.ToInt32(_textEncoding)));
        }
      }

    }





    public override DataTable GetSchema()
    {
      return base.GetSchema();
    }






    public override DataTable GetSchema(string collectionName)
    {
      return base.GetSchema(collectionName);
    }




    public override DataTable GetSchema(string collectionName, string[] restrictionValues)
    {
      return base.GetSchema(collectionName, restrictionValues);
    }


    
    

  }
}
